package de.QuizCommunity;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.Facebook.DialogListener;

import de.QuizCommunity.domain.Benutzer;
import de.QuizCommunity.service.Benutzer_Put;
import de.QuizCommunity.util.AppVariabels;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.Toast;

public class Login_Facebook extends Activity {
	
	public static Facebook facebook = new Facebook("423770474339347");
    private SharedPreferences mPrefs;
	
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
	 	mPrefs = PreferenceManager.getDefaultSharedPreferences(Login_Facebook.this); 
        String access_token = mPrefs.getString("access_token", null);
        long expires = mPrefs.getLong("access_expires", 0);
        
        if(access_token != null) {
            facebook.setAccessToken(access_token);
        }
        if(expires != 0) {
            facebook.setAccessExpires(expires);
        }

        if(!facebook.isSessionValid() || access_token==null) {

            facebook.authorize(this, new String[] {}, new DialogListener() {
                
                public void onComplete(Bundle values) {
                    SharedPreferences.Editor editor = mPrefs.edit();
                    editor.putString("access_token", facebook.getAccessToken());
                    editor.putLong("access_expires", facebook.getAccessExpires());
                    editor.commit();
                    
                    JSONObject response = null;
            		try {
            			response = Util.parseJson(facebook.request("/me", new Bundle(), "GET"));
            			JSONArray jArray = response.getJSONArray("data");
                		JSONObject json_data =null;
                		json_data = jArray.getJSONObject(0);

                		Benutzer benutzer = new Benutzer(0, json_data.getString("Email"), json_data.getString("Email"), 0, "", 0);
                		benutzer.setVorname( json_data.getString("firstname"));
                		Benutzer_Put.postBenutzer(benutzer);
                		AppVariabels.user = new Benutzer(0, json_data.getString("Email"), json_data.getString("Email"), 0, "", 0);
                		
            		
            		} catch (FacebookError e1) {
            			// TODO Auto-generated catch block
            			e1.printStackTrace();
            		} catch (FileNotFoundException e1) {
            			// TODO Auto-generated catch block
            			e1.printStackTrace();
            		} catch (MalformedURLException e1) {
            			// TODO Auto-generated catch block
            			e1.printStackTrace();
            		} catch (JSONException e1) {
            			// TODO Auto-generated catch block
            			e1.printStackTrace();
            		} catch (IOException e1) {
            			// TODO Auto-generated catch block
            			e1.printStackTrace();
            		}
            		
            		Intent in = new Intent(Login_Facebook.this,Menue.class);
        			startActivity(in);
                }
              
                public void onFacebookError(FacebookError error) {
                	SharedPreferences.Editor ed = mPrefs.edit();
        			ed.putString("access_token", null);
        			ed.commit();
        			
        			AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
        			mAsyncRunner.logout(getApplicationContext(), new RequestListener() {
        				  
        				  public void onComplete(String response, Object state) {}
        				  
        				  
        				  public void onIOException(IOException e, Object state) {}
        				  
        				  
        				  public void onFileNotFoundException(FileNotFoundException e,
        				        Object state) {}
        				  
        				  
        				  public void onMalformedURLException(MalformedURLException e,
        				        Object state) {}
        				  
        				  
        				  public void onFacebookError(FacebookError e, Object state) {}
        				});
        			
        			final Toast toastLogout= Toast.makeText(getApplicationContext(), "you aren't logged in...",Toast.LENGTH_LONG);
        			toastLogout.show();
        			Intent in = new Intent(Login_Facebook.this,Startseite.class);
        			startActivity(in);
                	
                }   
                
                public void onError(DialogError e) {
                	SharedPreferences.Editor ed = mPrefs.edit();
        			ed.putString("access_token", null);
        			ed.commit();
        			
        			AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
        			mAsyncRunner.logout(getApplicationContext(), new RequestListener() {
        				  
        				  public void onComplete(String response, Object state) {}
        				  
        				  
        				  public void onIOException(IOException e, Object state) {}
        				  
        				  
        				  public void onFileNotFoundException(FileNotFoundException e,
        				        Object state) {}
        				  
        				  
        				  public void onMalformedURLException(MalformedURLException e,
        				        Object state) {}
        				  
        				  
        				  public void onFacebookError(FacebookError e, Object state) {}
        				});
        			
        			final Toast toastLogout= Toast.makeText(getApplicationContext(), "you aren't logged in...",Toast.LENGTH_LONG);
        			toastLogout.show();
        			Intent in = new Intent(Login_Facebook.this,Startseite.class);
        			startActivity(in);
                }
    
                public void onCancel() {
        			Intent in = new Intent(Login_Facebook.this,Startseite.class);
        			startActivity(in);
        			final Toast toastLogin= Toast.makeText(getApplicationContext(), "you aren't logged in...",Toast.LENGTH_LONG);
            		toastLogin.show();
            		
                }
                              
            });
        }
        else{
        	
        	JSONObject response = null;
     		JSONObject jo =null;
        	try {
			response = Util.parseJson(facebook.request("/me", new Bundle(), "GET"));
			
    		Benutzer benutzer = new Benutzer(0, response.getString("email"),  response.getString("email"), 0, "", 0);
    		benutzer.setVorname(response.getString("first_name"));
    		Benutzer_Put.postBenutzer(benutzer);
    		AppVariabels.user = new Benutzer(0, response.getString("email"),  response.getString("email"), 0, "", 0);
    		AppVariabels.user.setVorname(response.getString("first_name"));
        	Intent in = new Intent(Login_Facebook.this,Menue.class);

			startActivity(in);
        	} catch (FacebookError e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        	
		
		
	}

}
